package com.feng.vhr.auth;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.feng.vhr.common.RespBean;
import com.feng.vhr.response.RHr;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class MySuccessHandler implements AuthenticationSuccessHandler{

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        //以json格式返回
        String username = httpServletRequest.getParameter("username");
        System.out.println(username);
        httpServletResponse.setContentType("application/json;charset=utf-8");
        PrintWriter out = httpServletResponse.getWriter();
        RHr rhr = (RHr) authentication.getPrincipal();
        rhr.setPassword(null);
        httpServletRequest.getSession().setAttribute("user",rhr);
        RespBean ok = RespBean.ok("登录成功!", rhr);
        String s = new ObjectMapper().writeValueAsString(ok);
        out.write(s);
        out.flush();
        out.close();
    }
}
